import subprocess
import itertools
import re

class ifconfigParser(object):
	def __init__(self, command='/sbin/ifconfig'):
		self.command = command
		self.interfaces = [NetworkInterface(i[:10]) for i in self._call_ifconfig() if i]

	def __call__(self):
		"""Return a list of NetworkInterface object for each available network interface
		"""
		#print "ifconfigParser > call"
		old = self.interfaces
		new = self._call_ifconfig()
		list( itertools.starmap(self.update, zip(old, new)) ) # consume iterator
		return self.interfaces

	def _call_ifconfig(self):
		o = subprocess.Popen([self.command], stdout = subprocess.PIPE)
		responses = o.communicate()[0].split('\n\n')
		return [r for r in responses if r]

	def update(self, obj, string):
		ip = re.findall('inet addr:', string)
		rx = re.findall('RX bytes:([0-9]*) ', string)[0]
		tx = re.findall('TX bytes:([0-9]*) ', string)[0]
		obj.ip = ip
		obj.lastRX = obj.RX
		obj.lastTX = obj.TX
		obj.RX = int(rx)
		obj.TX = int(tx)
		return obj

class NetworkInterface(object):
	def __init__(self, name):
		self.name = name.strip()
		self.ip = '0.0.0.0'
		self.RX = 0
		self.TX = 0
		self.lastRX = 0
		self.lastTX = 0
		self.historyRX = [0]*200
		self.historyTX = [0]*200
		self.x = range(200)

	def __repr__(self):
		return self.name

	def updateDelta(self):
		def _delta(varname):
			return self.__dict__[varname] - self.__dict__['last'+varname]

		self.historyRX = self.historyRX[1:] +[ _delta('RX')]
		self.historyTX = self.historyTX[1:] +[ _delta('TX')]


if __name__ == "__main__":
	print(ifconfigParser()())
